package com.chongyuan.producer.task;

import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.chongyuan.producer.common.DeviceInfo;
import com.chongyuan.producer.common.RedisConstant;
import com.chongyuan.producer.util.RedisUtil;
import com.icafebutler.framework.util.DateUtil;

@Component
public class CheckDeviceStateTask {
	private static final Logger LOGGER = LoggerFactory.getLogger(CheckDeviceStateTask.class);

	// 每3分钟执行一次
	@Scheduled(cron = "0 0/3 * * * ?")
	public void execute() {
		try {
			Map<String, Object> map = RedisConstant.socektMap;
			System.out.println("自动结束遛狗任务开始");
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				DeviceInfo deviceInfo = (DeviceInfo) entry.getValue();
				if (deviceInfo.getIsRuning() && DateUtil.getSecondDiff(deviceInfo.getStartTime(), new Date()) > 60 * 30) {
					LOGGER.info("自动结束遛狗开始，设备号：" + deviceInfo.getDeviceId());
					System.out.println("自动结束遛狗开始，设备号：" + deviceInfo.getDeviceId());
					String uploadReply = "[CY*" + deviceInfo.getDeviceId() + "*0001*" + "000b*UPLOAD" + ",1800]";
					RedisUtil.setObject(RedisConstant.DEVICE_DOG_IS_RUN + deviceInfo.getDeviceId(), "false", 60 * 60 * 2);
					// 发送停止遛狗指令
					deviceInfo.getHandler().sendClientMsg(uploadReply);
					deviceInfo.setIsRuning(false);
					RedisConstant.socektMap.put(RedisConstant.DEVICE_SOCKET_CLIENT + deviceInfo.getDeviceId(), deviceInfo);
					LOGGER.info("自动结束遛狗完成，设备号：" + deviceInfo.getDeviceId());
					System.out.println("自动结束遛狗完成，设备号：" + deviceInfo.getDeviceId());
				}
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
}
